-- 破盾打击

local HumanBone = TaleWorlds.Core.HumanBone
local EquipmentIndex = TaleWorlds.Core.EquipmentIndex
local Colors = TaleWorlds.Library.Colors
local SkinVoiceManager = TaleWorlds.MountAndBlade.SkinVoiceManager

local onlyPlayer = true
local percent = 0.9 --破盾概率
local behavior

return {
onBeforeMissionBehaviorInitialize = function (mission)
    behavior = SubModule:CreateMissionBehavior({
        onAgentHit = function (affectedAgent, affectorAgent, affectorWeapon, blow, attackCollisionData)
            if blow.IsMissile or not affectedAgent.IsHuman or affectedAgent == affectorAgent or affectorAgent == nil or (onlyPlayer and not affectorAgent.IsMainAgent) or blow.InflictedDamage > 0 then
                return
            end
            for i = 0, 4, 1 do
                local w = affectedAgent.Equipment[i]
                if not w.IsEmpty and w.CurrentUsageItem.IsShield and MBRandom.RandomFloat <= percent then
                    affectorAgent:MakeVoice(SkinVoiceManager.VoiceType.Yell, SkinVoiceManager.CombatVoiceNetworkPredictionType.NoPrediction)
                    behavior:SetTimeout(200, function (dt)
                        if affectorAgent.IsMainAgent then
                            InformationManager.DisplayMessage(InformationMessage("触发破盾！", Colors.Cyan))
                        end

                        local num = System.Enum.ToObject(EquipmentIndex.None:GetType(), i)
                        affectedAgent:ChangeWeaponHitPoints(num, 0)
                        affectedAgent:RemoveEquippedWeapon(num)

                        SubModule:CreateParticleSystemAttachedToBone(affectedAgent.AgentVisuals, "psys_game_shield_break", HumanBone.HandL)
                        
                        local id = string.contains(w.CurrentUsageItem.PhysicsMaterial, "metal") and SoundEvent.GetEventIdFromString("event:/mission/combat/shield/metal_broken")
                                                                                                 or SoundEvent.GetEventIdFromString("event:/mission/combat/shield/broken")
                        affectedAgent.Mission:MakeSound(id, affectedAgent.Position, false, true, affectorAgent.Index, affectedAgent.Index)
                        affectedAgent.Mission:AddSoundAlarmFactorToAgents(affectorAgent.Index, affectorAgent.Position, 15)
                    end)
                end
            end
        end
    })
    mission:AddMissionBehavior(behavior)
end
}
